/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.stylefeng.guns.modular.grape.service;

import cn.stylefeng.guns.core.common.exception.BizExceptionEnum;
import static cn.stylefeng.guns.core.util.UuidUtil.get32UUID;
import cn.stylefeng.guns.modular.grape.entity.Authentication;
import cn.stylefeng.guns.modular.grape.enums.AuthEnum;
import static cn.stylefeng.guns.modular.grape.enums.AuthEnum.getByName;
import static cn.stylefeng.guns.modular.grape.enums.StatusEnum.DELETED;
import cn.stylefeng.guns.modular.grape.mapper.AuthenticationMapper;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import static java.util.Calendar.getInstance;
import java.util.Date;
import static java.util.Objects.nonNull;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author wmao
 */
@Service
public class AuthenticationService extends ServiceImpl<AuthenticationMapper, Authentication> {

    @Resource
    private AuthenticationMapper authenticationMapper;
    
    @Transactional(rollbackFor = Exception.class)
    public void addAuth(Authentication auth) {
        if (ToolUtil.isOneEmpty(auth, auth.getKeyInfo(), auth.getUrl(), auth.getType(), auth.getUserName())) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        Date currentTime = getInstance().getTime();
        auth.setId(get32UUID());
        auth.setCreateTime(currentTime);
        auth.setUpdateTime(currentTime);
        Authentication old = getByType(getByName(auth.getType()));
        if(nonNull(old)){
            deleteAuth(old.getId());
        }
        this.save(auth);
    }
    
    @Transactional(rollbackFor = Exception.class)
    public void editAuth(Authentication auth) {
        if (ToolUtil.isOneEmpty(auth, auth.getType(), auth.getUserName())) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        auth.setUpdateTime(getInstance().getTime());
        this.updateById(auth);
    }
    
    @Transactional
    public void deleteAuth(String authId) {
        Authentication auth = authenticationMapper.selectById(authId);
        auth.setKeyInfo(auth.getKeyInfo() + "-deleted");
        auth.setUrl(auth.getUrl() + "-deleted");
        auth.setStatus(DELETED.getIdx());
        auth.setUpdateTime(getInstance().getTime());
        this.updateById(auth);
    }
    
    public Authentication getByType(AuthEnum auth){
        return nonNull(auth) ? authenticationMapper.findByType(auth.getName()) : null;
    }
}
